package cn.tedu.vue_master.oauth2;

import lombok.RequiredArgsConstructor;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

/**
 * 认证服务配置
 */
@Configuration
@EnableAuthorizationServer
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
//@ComponentScan("cn.wjc.demo.auth.service")
public class OAuthServerConfiguration extends AuthorizationServerConfigurerAdapter {

    private final AuthenticationManager authenticationManager;

    /**
     * 客户端服务
     */
    private final OAuthClientService oAuthClientService;

    private final TokenStore tokenStore;

    private final JwtAccessTokenConverter jwtAccessTokenConverter;

    private final PasswordEncoder passwordEncoder;

    /**
     * accessToken 过期时间 30天
     */
    private int accessExpireTimeInSecond = 60 * 60 * 24 * 30;

    /**
     * refreshToken 过期时间 1天
     */
    private int refreshExpireTimeInSecond = 60 * 60 * 24 * 1;

    /**
     * 生成 token 的处理
     */
    @Primary
    @Bean
    public DefaultTokenServices defaultTokenServices() {
        DefaultTokenServices tokenServices = new DefaultTokenServices();
        // 设置令牌生成机制(创建令牌的方式，存储用户状态信息的方式)
        tokenServices.setTokenStore(tokenStore);
        // 设置令牌增强(改变默认令牌创建方式，没有这句话默认是UUID)
        tokenServices.setTokenEnhancer(jwtAccessTokenConverter);
        // 是否支持 refreshToken
        tokenServices.setSupportRefreshToken(true);
        // 是否复用 refreshToken，不复用的话是每次都会刷新token
        tokenServices.setReuseRefreshToken(true);
        // token 有效期自定义设置，默认12小时
        tokenServices.setAccessTokenValiditySeconds(accessExpireTimeInSecond);
        // 默认 30 天，这里修改
        tokenServices.setRefreshTokenValiditySeconds(refreshExpireTimeInSecond);
        return tokenServices;
    }

    /**
     * 提供一个认证的入口（客户端去哪里认证）
     *
     * @param security
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        // 开启 /oauth/token_key 验证端口无权限访问
        // 对外发布认证入口(/oauth/token),认证通过服务端会生成一个令牌
        security.tokenKeyAccess("permitAll()");
        // 开启 /oauth/check_token 验证端口认证权限访问
        // 对外发布检查令牌的入口(/oauth/check_token)
        security.checkTokenAccess("permitAll()");
        // 开启后请求需要带上 client_id client_secret
        // 允许用户通过表单方式提交认证,完成认证
        security.allowFormAuthenticationForClients();
    }

    /**
     * 定义客户端应该携带什么信息去认证
     * 指明哪些对象可以到这里进行认证(哪个客户端对象需要什么特点)
     *
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.withClientDetails(clientDetailsService());
        /*clients.inMemory().withClient("5099c23e45f64c158065e1b062492357").secret(this.passwordEncoder.encode("f5b351eb6df8458382d0303aae8a72d7275a2296ff45488c9f135ca120edebd1"))
                .authorizedGrantTypes("password")		//授权类型指定为password
                .scopes("all");*/
    }

    @Bean
    public ClientDetailsService clientDetailsService() {
        return oAuthClientService::loadClientByClientId;
    }

    /**
     * 提供一个负责认证授权的对象
     * (完成客户端认证后会颁发令牌，默认令牌格式是uuid方式的)
     *
     * @param endpoints
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.tokenStore(tokenStore)
                .authenticationManager(authenticationManager)
                // 设置令牌业务对象(此对象提供令牌创建及有效机制设置)
                .tokenServices(defaultTokenServices())
                // 设置允许对哪些请求方式进行认证(默认支支持post):可选
                // 获取token支持get方式和post方式
                .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);
    }
}
